package base;

import gtools.GTools;

import instructions.Instruction;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

import parser.Parser;
import parser.ST2AST;

import slip.trees.TreeNode;

import lexer.Lexer;

public class Brain {

	public static void main(String args[]) {

		String filename;

		if (args.length > 0) {
			filename = args[0];

			try {

				String code = readFile(filename);
				GTools gt = new GTools("Gr17Grammar.txt", "Gr17");
				Lexer lex = new Lexer(code, gt);
				TreeNode root = Parser.parse(lex, gt);
				Instruction astroot = ST2AST.tradProgram(root);
				Interpreter.instr(astroot);
				
			} catch (IOException e) {
				System.err.println("Problem reading " + filename);
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else
			System.out.println("I need a file to execute !");

	}

	private static String readFile(String path) throws IOException {
		FileInputStream stream = new FileInputStream(new File(path));
		try {
			FileChannel fc = stream.getChannel();
			MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0,
					fc.size());
			/* Instead of using default, pass in a decoder. */
			return Charset.defaultCharset().decode(bb).toString();
		} finally {
			stream.close();
		}
	}
}
